package com.dries.portal.module.wechat.wxma.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.dries.common.api.CommonResult;
import com.dries.portal.module.wechat.wxma.config.WxMaConfig;
import com.dries.portal.module.user.entity.UserEntity;
import com.dries.portal.module.wechat.wxma.form.WxGetPhoneForm;
import com.dries.portal.module.wechat.wxma.form.WxMaLoginForm;
import com.dries.portal.module.user.service.UserCacheService;
import com.dries.portal.module.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 微信小程序用户接口
 * @Author ZSY
 * @createTime 2020/6/24 14:02
 */
@Slf4j
@RestController
@Api(tags = "微信小程序用户接口", value = "微信小程序用户接口")
@RequestMapping("/portal/wx/user")
public class WxMaUserController {

    @Resource
    private UserService userService;
    @Resource
    private UserCacheService userCacheService;

    /**
     * 登陆接口
     */
    @ApiOperation(value = "微信登陆接口")
    @PostMapping("/login")
    public CommonResult login(@Valid @RequestBody WxMaLoginForm loginForm) {

        final WxMaService wxMaService = WxMaConfig.getMaService(loginForm.getAppId());

        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(loginForm.getCode());
            //            使用AppId获取OpenID，SessionKey
            //            log.info(session.getSessionKey());
            //            log.info(session.getOpenid());
            // 用户信息校验
            if (!wxMaService.getUserService().checkUserInfo(session.getSessionKey(), loginForm.getRawData(), loginForm.getSignature())) {
                return CommonResult.failed("user check failed");
            }
            // 解密用户信息
            WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(session.getSessionKey(), loginForm.getEncryptedData(), loginForm.getIv());
            log.info("微信用户信息=============》{}", userInfo);
            String token;
            //            log.info("====================》" + JSONUtil.toJsonStr(user));
            UserEntity user = userService.getUserByOpenId(session.getUnionid());

            if (user != null) {
                token = userService.loginByOpenId(session.getOpenid());
                Map<String, Object> map = new HashMap<>();
                map.put("token", token);
                map.put("userInfo", user);
                return CommonResult.success(map);
            } else {
                // 注册用户绑定用户信息,即注册
                return userService.register(userInfo);
            }
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
            return CommonResult.failed(e.getMessage());
        }
    }

    /**
     * <pre>
     * 获取用户信息接口
     * </pre>
     */
    @GetMapping("/info")
    public CommonResult info(String appid, String sessionKey,
                             String signature, String rawData, String encryptedData, String iv) {

        final WxMaService wxService = WxMaConfig.getMaService(appid);

        // 用户信息校验
        if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            return CommonResult.failed("user check failed");
        }

        // 解密用户信息
        WxMaUserInfo userInfo = wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);

        return CommonResult.success(userInfo);
    }

    /**
     * <pre>
     * 获取用户绑定手机号信息
     * </pre>
     */
    @ApiOperation(value = "获取用户绑定手机号信息")
    @PostMapping("/phone")
    public CommonResult phone(Principal principal, @RequestBody WxGetPhoneForm phoneForm) throws WxErrorException {
        log.info("appID: {}",phoneForm.getAppId());
        final WxMaService wxMaService = WxMaConfig.getMaService(phoneForm.getAppId());

        WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(phoneForm.getCode());

        // 解密
        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(session.getSessionKey(), phoneForm.getEncryptedData(), phoneForm.getIv());

        log.info("【用户手机号=================》】{}", phoneNoInfo);

        UserEntity user = userService.getByUsername(principal.getName()).getData();
        user.setMobile(phoneNoInfo.getPhoneNumber());

        userService.saveOrUpdate(user);
        userCacheService.setUser(user);

        return CommonResult.success(user);
    }

}
